<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item :table-form-merge="2" label="申请时间:">
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="所属机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item label="费用类型:" prop="paymentChannel">
        <el-select v-model="query.feeType" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in feeTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态:" prop="payType">
        <el-select v-model="query.billStatus" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in billStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <el-button v-permission="2" type="primary" icon="el-icon-circle-plus" @click="addFee">新增</el-button>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      highlight-current-row
      pagination
      :total="tableData.total"
      custom-column
      :immediate-fetch="false"
      @fetch="fetchData"
    />
    <addFee ref="add" :fee-type-map="feeTypeMap" @updateDate="search" />
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { queryMap, queryFeeList, auditFee, cancelFee, detailFee, noAuditFee } from '@/api'
  import moment from 'dayjs'
  import { mapGetters } from 'vuex'
  import addFee from './components/add.vue'
  export default {
    name: 'feeRegistration',
    components: {
      addFee
    },
    data() {
      return {
        date: [],
        treeData: [],
        billStatusMap: [{ desc: '待审核', value: 1 }, { desc: '已审核', value: 2 }],
        feeTypeMap: [],
        query: {
          orgSNNo: '',
          feeType: null,
          billStatus: null
        },
        tableData: {
          data: [],
          column: [
            {
              fixed: 'left',
              type: 'index'
            },
            {
              prop: 'billCode',
              fixed: 'left',
              label: '单据编号',
              width: 200,
              render: (h, { row }) => row.billCode ? <el-link underline={false} onClick={() => this.openDetail(row)}>{row.billCode}</el-link> : <span>{row.billCode}</span>
            },
            {
              prop: 'feeType',
              fixed: 'left',
              label: '费用类型',
              render: (h, { row }) => <span>{ row.feeType && formatColumnMap(this.feeTypeMap, 'value', row.feeType, 'desc') }</span>
            },

            {
              prop: 'fee',
              align: 'right',
              label: '费用金额'
            },
            {
              prop: 'billStatus',
              width: 120,
              align: 'right',
              label: '状态',
              render: (h, { row }) => <span>{ row.billStatus && formatColumnMap(this.billStatusMap, 'value', row.billStatus, 'desc') }</span>
            },
            {
              prop: 'orgName',
              label: '所属机构',
              width: 200
            },
            {
              prop: 'createTime',
              label: '创建时间',
              width: 180,
              render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'createUser',
              width: 120,
              align: 'right',
              label: '创建人'
            },
            {
              prop: 'auditDt',
              label: '审核时间',
              width: 180,
              render: (h, { row }) => <span>{ row.auditDt && parseTime(row.auditDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'auditor',
              width: 120,
              align: 'right',
              label: '审核人'
            },
            {
              prop: 'remark',
              label: '备注'
            },
            {
              label: '操作',
              className: 'action-col',
              width: 80,
              align: 'center',
              fixed: 'right',
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-dropdown>
                      <span class='el-dropdown-link'>
                        更多<i class='el-icon-arrow-down el-icon--right'></i>
                      </span>
                      <el-dropdown-menu slot='dropdown'>
                        {(<el-dropdown-item>
                          <el-link v-permission='3' v-show={row.billStatus === 1} underline={false} size='mini' onClick={() => this.edit(row, 'edit')}>
                            编辑
                          </el-link>
                        </el-dropdown-item>)}
                      {(
                        <el-dropdown-item>
                          <el-link v-permission='4' v-show={row.billStatus === 1} underline={false} size='mini' onClick={() => this.audit(row, 'audit')}>
                            审核
                          </el-link>
                        </el-dropdown-item>)}
                      {(
                        <el-dropdown-item>
                          <el-link v-permission='5' v-show={row.billStatus === 1} underline={false} size='mini' onClick={() => this.remove(row, 'remove')}>
                            删除
                          </el-link>
                        </el-dropdown-item>)}
                      {(
                        <el-dropdown-item>
                          <el-link v-permission='7' v-show={row.billStatus === 2} underline={false} size='mini' onClick={() => this.noAudit(row)}>
                            反审核
                          </el-link>
                        </el-dropdown-item>)}
                      {(
                        <el-dropdown-item>
                          <el-link v-permission='6' underline={false} size='mini' onClick={() => this.tryPrint(row)}>
                            打印
                          </el-link>
                        </el-dropdown-item>)}
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>
                )
              }
            }
          ]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await this.getTimeFn()
      await Promise.all([this.getTreeData(), this.queryOptionsMap()])
      this.$refs.lbTable.fetch({ currentPage: 1 })
    },

    methods: {
      getTimeFn() {
        const end = new Date()
        const start = new Date()
        // start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        this.date[0] = parseTime(start, '{y}-{m}-{d}') + ' 00:00:00'
        this.date[1] = parseTime(end, '{y}-{m}-{d}') + ' 23:59:59'
      },
      // 查询字典枚举
      async queryOptionsMap() {
        const [res1] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'Acc_FeeRegisterType' })
        ])
        this.feeTypeMap = res1.data // 费用类型
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.createTime = moment(this.date[0]).format()
          query.createTimeEnd = moment(this.date[1]).format()
        }
        // const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        // if (diff > 93) {
        //   this.$message.error('最大支持查询3个月')
        //   return
        // }
        const res = await queryFeeList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 详情
      openDetail(row) {
        this.$refs.add.open(row, '详情')
      },
      // 新增
      addFee() {
        this.$refs.add.open()
      },
      // 编辑
      edit(row, type) {
        this.$refs.add.open(row)
      },
      // 审核
      audit(row, type) {
        this.$confirm(`您确认审核吗?`, '提示', {
          type: 'warning'
        }).then(() => {
          auditFee({ billCode: row.billCode }).then(res => {
            this.$notify({
              title: '提示',
              message: `操作成功`,
              type: 'success',
              duration: 2000
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }).catch(() => {})
        }).catch(() => {
          this.$message.info('已取消')
        })
      },
      // 反审核
      noAudit(row, type) {
        this.$confirm(`您确认反审核吗?`, '提示', {
          type: 'warning'
        }).then(() => {
          noAuditFee({ billCode: row.billCode }).then(res => {
            this.$notify({
              title: '提示',
              message: `操作成功`,
              type: 'success',
              duration: 2000
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }).catch(() => {})
        }).catch(() => {
          this.$message.info('已取消')
        })
      },
      // 删除
      remove(row, type) {
        this.$confirm(`您确认删除吗?`, '提示', {
          type: 'warning'
        }).then(() => {
          cancelFee({ billCode: row.billCode }).then(res => {
            this.$notify({
              title: '提示',
              message: `操作成功`,
              type: 'success',
              duration: 2000
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }).catch(() => {})
        }).catch(() => {
          this.$message.info('已取消')
        })
      },
      async tryPrint(row) {
        const params = {
          billCode: row.billCode
        }
        const { status, data } = await detailFee(params)
        if (status === 200) {
          this.print(row, data)
        }
      },
      print(row, resdata) {
        const cache = JSON.parse(localStorage.tp)
        if (!cache) {
          this.$message.warning('请先设置打印模板')
          return
        }
        var temp = ''
        if (row.feeType === 2) {
          temp = cache['34']
        } else {
          temp = cache['35']
        }
        if (!temp) {
          this.$message.warning('请先设置打印模板')
          return
        }
        row.createDt = moment(resdata.openDt).format('YYYY-MM-DD')
        row.createDt2 = moment(row.auditDt).format('YYYY  MM  DD')
        row.remark = '气瓶赔偿费' + row.fee + '元'
        // row.feeType = `${formatColumnMap(
        //   this.feeTypeMap,
        //   'value',
        //   row.feeType,
        //   'desc'
        // )}`

        let printcmd = {
          cmd: 2,
          title: `正在对气瓶提取单${row.billCode}进行打印`,
          elements: []
        }
        printcmd = { ...printcmd, ...temp }

        if (!window.jCPrint || !window.jCPrint.ws) {
          this.$message.error('打印未连接')
          return
        }
        window.jCPrint.process(printcmd, temp, row, resdata)
        if (window.jCPrint.firePush(JSON.stringify(printcmd))) {
          this.$message.success('打印指令已发送')
        } else {
          this.$message.error('打印未连接')
        }
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
